#!/usr/bin/env python

# SPDX-License-Identifier: GPL-2.0-or-later
# SPDX-FileCopyrightText: 2025 Joshua Murphy <flightgear@joshmurphy.ca>

import random
import webbrowser
import http.server
import socketserver
import os
import sys

def main():
    if len(sys.argv) != 2:
        print("Usage: python script.py <directory>")
        sys.exit(1)

    directory = sys.argv[1]
    if not os.path.isdir(directory):
        print(f"Error: {directory} is not a valid directory.")
        sys.exit(1)

    # Create a web server to better approximate how relative path-handling for documentation will
    # work in a production setting, as well as to make the cookie that stores the theme preference
    # work correctly.

    os.chdir(directory)
    port = random.randint(8000, 9000)
    handler = http.server.SimpleHTTPRequestHandler

    try:
        with socketserver.TCPServer(("", port), handler) as httpd:
            print(f"Serving {directory} at http://localhost:{port}")
            webbrowser.open(f'http://localhost:{port}')

            try:
                httpd.serve_forever()
            except KeyboardInterrupt:
                print("\nServer shutting down...")
                httpd.server_close()
    except OSError as e:
        print(f"Error: Port {port} is already in use.")
        sys.exit(1)

if __name__ == "__main__":
    main()